<?php

namespace App\Store\Models\Order;

use App\Admin\Models\SiteCompany;
use App\Common\Services\Common;
use App\Common\Services\Date\TimerRange;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;
use App\Store\Models\Account\Account;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Sysset\Classesset;

class OrderSales extends Model
{
    protected $table = 'site_order_sales';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    public function getMixedPaymentAttribute($value)
    {
        return empty($value) ? null : json_decode($value, true); // 将JSON字符串转换为PHP数组
    }

    /**
     *获取列表
     */
    public static function getList(Request $request)
    {

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['memberinfo', 'shoppingaccountinfo1', 'shoppingaccountinfo2', 'storeinfo', 'goodslist', 'recoverygoodslist', 'sendgoodslist'])
            ->where(['cp_id' => $cp_id, 'is_del' => 1])->orderBy('order_at', 'desc');

        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if ($store_ids) {//权限控制
            if (is_array($store_ids)) {//获取当前权限下的门店
                $query->whereIn('store_id', $store_ids);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) {//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        if (count($ids) > 0) {
            $query->whereIn('id', $ids);
        }


        $real_name = $request->real_name;
        if ($real_name != '') {
            $ids = Member::where('real_name', 'like', '%' . $real_name . '%')->where('is_del', 1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $mobile = $request->mobile;
        if ($mobile != '') {
            $ids = Member::where('mobile', 'like', '%' . $mobile . '%')->where('is_del', 1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $mem_card_no = $request->mem_card_no;
        if ($mem_card_no != '') {
            $ids = Member::where('mem_card_no', 'like', '%' . $mem_card_no . '%')->where('is_del', 1)->pluck('id');
            $query->whereIn('mem_id', $ids);
        }

        $store_id = intval($request->store_id);//门店
        if ($store_id > 0) {
            $query->where('store_id', $store_id);
        }

        // $is_maker = intval($request->is_maker);//挂单
        // if ($is_maker>0) {
        //     $query->where('is_maker',$is_maker);
        // }


        $ispay = intval($request->ispay);//挂单
        if ($ispay > 0) {
            if ($ispay == 1) {
                $query->whereIn('is_maker', [0, 1]);
            } else {
                $query->where('is_maker', 2);
            }

        }
        $mem_id = intval($request->mem_id);//获取指定用户的积分记录
        if ($mem_id > 0) {
            $query->where('mem_id', $mem_id);
        }

        $audit_status = intval($request->audit_status);//获取审核状态
        if ($audit_status > 0) {
            $query->where('audit_status', $audit_status);
        } else {
            $query->whereIn('audit_status', [1, 2]);
        }
        $order_sn = $request->order_sn;
        if ($order_sn != '') {
            $query->where('order_sn', 'like', '%' . $order_sn . '%');
        }

        $shopping_account_id1 = intval($request->shopping_account_id1);
        if ($shopping_account_id1 > 0) {
            $query->where('shopping_account_id1', $shopping_account_id1);
        }

        $shopping_account_id2 = intval($request->shopping_account_id2);
        if ($shopping_account_id2 > 0) {
            $query->where('shopping_account_id2', $shopping_account_id2);
        }

        $classesset_id = intval($request->classesset_id);
        if ($classesset_id > 0) {
            $query->where('classesset_id', $classesset_id);
        }

        $real_money_min = intval($request->real_money_min);
        $real_money_max = intval($request->real_money_max);
        if ($real_money_min >= 0 && $real_money_min < $real_money_max) {
            $query->where('real_money', '>=', $real_money_min)->where('real_money', '<=', $real_money_max);
        }


        $is_maker = intval($request->is_maker);//查询挂单订单
        if ($is_maker == 2) {
            $query->where('is_maker', 2);
        }
        // $red_status=intval($request->red_status);//查询红冲订单
        // if($red_status>0){
        //     $query->where('red_status',$red_status);
        // }
        // $red_audit_status=intval($request->red_audit_status);//查询红冲审核状态
        // if($red_audit_status>0){
        //     $query->where('red_audit_status',$red_audit_status);
        // }


        $timerangetype = intval($request->timerangetype);//今日、本周、本月
        if (in_array($timerangetype, [1, 2, 3])) {
            if ($timerangetype == 1) {
                $time_res = TimerRange::getToday();
                $query->whereBetween('order_at', [$time_res['start_time'], $time_res['end_time']]);
            }

            if ($timerangetype == 2) {
                $time_res = TimerRange::getThisWeek();
                $query->whereBetween('order_at', [$time_res['start_time'], $time_res['end_time']]);
            }

            if ($timerangetype == 3) {
                $time_res = TimerRange::getThisMonth();
                $query->whereBetween('order_at', [$time_res['start_time'], $time_res['end_time']]);
            }
        }


        $start_time = strtotime($request->start_time) > 0 ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = strtotime($request->end_time) > 0 ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > $start_time) {
            $query->where('order_at', '>=', $start_time)->where('order_at', '<=', $end_time);
        }

        $training_min = $request->training_min ?? 0;
        $training_max = $request->training_max ?? 0;
        if ($training_min > 0 || $training_max > 0) {
            $query->where('real_money', '>=', $training_min)->where('real_money', '<=', $training_max);
        }

        $isgetall = intval($request->isgetall) ?? 0;
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    /**
     * 获取销售商品列表
     */
    public function goodslist()
    {
        return $this->hasMany(OrderSalesGoods::class, 'pid', 'id')->where(['is_del' => 1]);
    }

    public function memberinfo()
    {
        return $this->hasOne(Member::class, 'id', 'mem_id')->where('is_del', 1);
    }

    public function shoppingaccountinfo1()
    {

        return $this->hasOne(Account::class, 'id', 'shopping_account_id1');
    }

    public function shoppingaccountinfo2()
    {

        return $this->hasOne(Account::class, 'id', 'shopping_account_id2');
    }

    public function storeinfo()
    {

        return $this->hasOne(SiteStore::class, 'id', 'store_id');
    }

    public function companyinfo()
    {
        return $this->hasOne(SiteCompany::class, 'id', 'cp_id');
    }


    public function recoverygoodslist()
    {
        return $this->hasMany(OrderSalesRecoveryGoods::class, 'pid', 'id')->where(['is_del' => 1]);
    }

    public function sendgoodslist()
    {
        return $this->hasMany(OrderSalesSendGoods::class, 'pid', 'id')->where(['is_del' => 1]);
    }

    public function classessetinfo()
    {
        return $this->hasOne(Classesset::class, 'id', 'classesset_id');
    }

    public function paytypeinfo()
    {
        return $this->hasOne(PaytypeList::class, 'id', 'pay_type_id');
    }


    /**
     * @param $cp_id
     * @param $mem_id
     * @return mixed[]
     */
    public static function getListByMem($cp_id, $mem_id)
    {
        return  self::with(['storeinfo', 'goodslist'])
            ->where(['cp_id' => $cp_id, 'mem_id' => $mem_id, 'is_del' => 1])
            ->where('audit_status','<>',3)
            ->get()
            ->toArray();
    }
}
